package com.example.weight.wormHandle.garbageDisposal.onsiteDispose;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class WormHatching extends AppCompatActivity implements View.OnClickListener{
    private String name, factory;
    private TitleBar titleBar;

    private TextView incoming_date;
    private TextView incoming_week;
    private TextView hatching_date;
    private TextView worm_out_date;
    private EditText hatching_box_num;
    private EditText hatching_days;
    private EditText worm_out_batches;
    private EditText weight_1_4;
    private EditText weight_5_6;
    private EditText weight_7_8;
    private EditText worm_egg_weight;
    private EditText all_feed_weight;
    private EditText remark;

    String activeButton = new String();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    SimpleDateFormat weekOfDaySDF = new SimpleDateFormat("EEEE");
    Date incomingDate = new Date(System.currentTimeMillis());
    Date hatchingDate = new Date(System.currentTimeMillis());
    Date wormoutDate = new Date(System.currentTimeMillis());
   static Calendar calendar= Calendar.getInstance(Locale.CHINA);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.worm_hatching);
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                WormHatching.this.finish();
            }

            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });
        incoming_date = findViewById(R.id.worm_hatching_incomingDate);
        incoming_date.setOnClickListener(this);

        incoming_week = findViewById(R.id.worm_hatching_incomingWeek);

        hatching_date = findViewById(R.id.worm_hatching_hatchingDate);
        hatching_date.setOnClickListener(this);

        worm_out_date = findViewById(R.id.worm_out_date);
        worm_out_date.setOnClickListener(this);

        hatching_box_num = findViewById(R.id.hatching_box_num);
        hatching_days = findViewById(R.id.hatching_days);

        worm_out_batches = findViewById(R.id.worm_out_batches);
        weight_1_4 = findViewById(R.id.weight_1_4);
        weight_5_6 = findViewById(R.id.weight_5_6);
        weight_7_8 = findViewById(R.id.weight_7_8);
        worm_egg_weight = findViewById(R.id.worm_egg_weight);
        all_feed_weight = findViewById(R.id.all_feed_weight);
        remark = findViewById(R.id.worm_hatching_remark);

        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/kitchenwaste/hatching/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            Log.d("jy",response.toString());
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id")) {
                                    incoming_date.setText(data.getString("incomingdate"));
                                    hatching_date.setText(data.getString("hatchingdate"));
                                    incoming_week.setText(data.getString("incomingweek"));
                                    hatching_box_num.setText(data.getString("hatchingboxnum"));
                                    hatching_days.setText(data.getString("hatchingdays"));
                                    worm_out_date.setText(data.getString("wormoutdate"));
                                    worm_out_batches.setText(data.getString("wormoutbatches"));
                                    weight_1_4.setText(data.getString("weight14"));
                                    weight_5_6.setText(data.getString("weight56"));
                                    weight_7_8.setText(data.getString("weight78"));
                                    worm_egg_weight.setText(data.getString("wormeggweight"));
                                    all_feed_weight.setText(data.getString("allfeedweight"));
                                    remark.setText(data.getString("remark"));
                                    Toast.makeText(WormHatching.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                incoming_date.setText(simpleDateFormat.format(incomingDate));
                                incoming_week.setText(weekOfDaySDF.format(incomingDate));
                                hatching_date.setText(simpleDateFormat.format(hatchingDate));
                                worm_out_date.setText(simpleDateFormat.format(wormoutDate));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(WormHatching.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
        switch (activeButton){
            case "weight_1_4_btn":
                weight_1_4.setText(weight);
                break;
            case "weight_5_6_btn":
                weight_5_6.setText(weight);
                break;
            case "weight_7_8_btn":
                weight_7_8.setText(weight);
                break;
            case "worm_egg_weight_btn":
                worm_egg_weight.setText(weight);
                break;
            case "all_feed_weight_btn":
                all_feed_weight.setText(weight);
                break;
        }
    }
    public void goWeight(View view) {
        switch (view.getId()) {
            case R.id.weight_1_4_btn:
                activeButton = "weight_1_4_btn";
                break;
            case R.id.weight_5_6_btn:
                activeButton = "weight_5_6_btn";
                break;
            case R.id.weight_7_8_btn:
                activeButton = "weight_7_8_btn";
                break;
            case R.id.worm_egg_weight_btn:
                activeButton = "worm_egg_weight_btn";
                break;
            case R.id.all_feed_weight_btn:
                activeButton = "all_feed_weight_btn";
                break;
            default:
                break;
        }
        Intent intent = new Intent(WormHatching.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }
    public void save(View view) {
        if (incoming_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写到货日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (hatching_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_out_date.getText().toString().equals("")) {
            Toast.makeText(this, "请填写出虫日期", Toast.LENGTH_SHORT).show();
            return;
        }
        if (hatching_box_num.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化盒号", Toast.LENGTH_SHORT).show();
            return;
        }
        if (hatching_days.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化天数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_out_batches.getText().toString().equals("")) {
            Toast.makeText(this, "请填写出虫份数", Toast.LENGTH_SHORT).show();
            return;
        }
        if (weight_1_4.getText().toString().equals("")) {
            Toast.makeText(this, "请填写1-4d孵化料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (weight_5_6.getText().toString().equals("")) {
            Toast.makeText(this, "请填写5-6d培育料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (weight_7_8.getText().toString().equals("")) {
            Toast.makeText(this, "请填写7-8d培育料重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (worm_egg_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写孵化虫卵重量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (all_feed_weight.getText().toString().equals("")) {
            Toast.makeText(this, "请填写单份虫+料总重量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/kitchenwaste/hatching/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    JSONObject jsonObject = null;
                                    try {
                                        jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(WormHatching.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(WormHatching.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.d("jy", error.toString());
                            Toast.makeText(WormHatching.this, "保存失败", Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("incomingDate", incoming_date.getText().toString());
                            map.put("incomingWeek", incoming_week.getText().toString());
                            map.put("hatchingDate", hatching_date.getText().toString());
                            map.put("wormOutDate",  worm_out_date.getText().toString());
                            map.put("hatchingBoxNum", hatching_box_num.getText().toString());
                            map.put("hatchingDays", hatching_days.getText().toString());
                            map.put("wormOutBatches", worm_out_batches.getText().toString());
                            map.put("weight_1_4", weight_1_4.getText().toString());
                            map.put("weight_5_6",  weight_5_6.getText().toString());
                            map.put("weight_7_8", weight_7_8.getText().toString());
                            map.put("wormEggWeight", worm_egg_weight.getText().toString());
                            map.put("allFeedWeight", all_feed_weight.getText().toString());
                            map.put("remark", remark.getText().toString());
                            map.put("recorder",name);
                            map.put("factory",factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
    /**
     * 日期选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param c
     */
    public static void showDatePickerDialog(Activity activity, int themeResId, final TextView tv, final TextView weekView, Calendar c) {

        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        new DatePickerDialog(activity, themeResId, new DatePickerDialog.OnDateSetListener() {
            // 绑定监听器(How the parent is notified that the date is set.)
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                // 此处得到选择的时间，可以进行你想要的操作
                tv.setText(year + "/" +String.format("%02d", (monthOfYear + 1))  + "/" + String.format("%02d",dayOfMonth));
                c.set(year, monthOfYear, dayOfMonth);
                if(weekView!=null){
                    int week=c.get(Calendar.DAY_OF_WEEK);
                    String[]weeks={"","星期日","星期一","星期二","星期三","星期四","星期五","星期六"};
                    String xingqi=weeks[week];
                    weekView.setText(xingqi);
                }
            }
        }
                // 设置初始日期
                , calendar.get(Calendar.YEAR)
                , calendar.get(Calendar.MONTH)
                , calendar.get(Calendar.DAY_OF_MONTH)).show();
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.worm_hatching_incomingDate:
                showDatePickerDialog(this,  2, incoming_date, incoming_week, calendar);
                break;
            case R.id.worm_hatching_hatchingDate:
                showDatePickerDialog(this,  2, hatching_date, null, calendar);
                break;
            case R.id.worm_out_date:
                showDatePickerDialog(this,  2, worm_out_date, null, calendar);
                break;
            default:
                break;
        }
    }
    public static String getWeek(String w) {
        String week = "";
        switch(w){
            case "1":
            case "Monday":
                week = "星期一";
                break;
            case "2":
            case "Tuesday":
                week = "星期二";
                break;
            case "3":
            case "Wednesday":
                week = "星期三";
                break;
            case "4":
            case "Thursday":
                week = "星期四";
                break;
            case "5":
            case "Friday":
                week = "星期五";
                break;
            case "6":
            case "Saturday":
                week = "星期六";
                break;
            case "7":
            case "Sunday":
                week = "星期日";
                break;
        };
        return week;
    }
}
